<template>
  <el-row :gutter="10">
    <el-col :md="12" :sm="24">
      <el-card :bordered="false">
        <el-row style="margin-left: 14px">
          <el-button type="primary" v-hasPermi="['tms:category:add']" @click="handleAdd">添加</el-button>
          <el-button v-hasPermi="['tms:category:remove']" @click="handleDelete">批量删除</el-button>
          <el-button @click="refresh">刷新</el-button>
        </el-row>
        <div
          style="
            background: #fff;
            padding-left: 16px;
            height: 100%;
            margin-top: 5px;
          "
        >
          <el-alert type="info" show-icon>
            <span class="choose" style="font-size: 15px; color: #000"
              >当前选择：</span
            >
            <span style="font-size: 15px; color: #000">{{
              getCurrSelectedTitle()
            }}</span>
            <a
              v-if="this.currSelected.title"
              style="margin-left: 10px; font-size: 15px; color: #18acff"
              @click="onClearSelected"
              >取消选择</a
            >
          </el-alert>
          <template>
            <el-dropdown>
              <el-dropdown-menu> </el-dropdown-menu>
              <el-tree
                :data="data"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="tree"
                highlight-current
                :props="defaultProps"
                :check-strictly="true"
                check-on-click-node
                @check="currentChecked"
                
              >
              </el-tree>
            </el-dropdown>
          </template>
        </div>
      </el-card>
    </el-col>
    <el-col :md="12" :sm="6">
      <el-card :bordered="false" v-if="this.goodsList.length > 0">
        <el-form ref="form" :model="form" :rules="rules" label-width="180px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="上级目录：" prop="parentId">
            <el-select
              class="main-select-tree"
              ref="selectTree"
              v-model="form.parentName"
              clearable
              @clear="setValueNull"
            >
              <el-option
                v-for="item in formatData(changeData)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                style="display: none"
              />
              <el-tree
                class="main-select-el-tree"
                ref="selecteltree"
                :data="changeData"
                node-key="id"
                highlight-current
                :props="defaultProps"
                @node-click="handleNodeClick"
                :current-node-key="treeName"
                :expand-on-click-node="expandOnClickNode"
                default-expand-all
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序：">
            <el-input-number v-model="form.sort" />
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-form-item>
        </el-form>
        <div class="form-btn">
          <el-button
            type="default"
            htmlType="button"
            icon="sync"
            @click="emptyCurrForm"
            >重置</el-button
          >
          <el-button type="primary" htmlType="button" icon="form" @click="Sure"
            >保存</el-button
          >
        </div>
      </el-card>
      <el-card v-else>
        <el-empty>
          <span slot="description"> 请先选择一个商品! </span>
        </el-empty>
      </el-card>
    </el-col>
    <el-dialog title="新增" :visible.sync="open" width="790px">
      <el-form ref="form" :rules="rules" :model="form" label-width="150px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="名称" prop="name">
              <el-input
                :style="{
                  border: look == false ? '' : '1px solid red',
                  borderRadius: look == false ? '' : '5px',
                }"
                @blur="updateRate"
                @focus="treeDate"
                v-model="form.name"
                placeholder="请输入商品名称"
              />
            </el-form-item>
            <div
              v-if="look"
              style="
                height: 20px;
                width: 100%;
                font-size: 8px;
                color: red;
                margin-top: -20px;
                margin-left: 156px;
              "
            >
              名称已经存在！
            </div>
            <el-form-item label="上级目录：" prop="parentId">
              <el-select
                clearable
                class="main-select-tree"
                ref="selectTree"
                v-model="form.parentId"
                style="width: 475px"
              >
                <el-option
                  v-for="item in formatData(data)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  style="display: none"
                />
                <el-tree
                  class="main-select-el-tree"
                  ref="selecteltree"
                  :data="data"
                  node-key="id"
                  highlight-current
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                  :current-node-key="treeName"
                  :expand-on-click-node="expandOnClickNode"
                  default-expand-all
                />
              </el-select>
            </el-form-item>
            <el-form-item label="排序：" prop="sort">
              <el-input-number controls-position="right" v-model="form.sort" />
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input type="textarea" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="form-btn">
        <el-button type="default" htmlType="button" icon="sync" @click="cancel"
          >关闭</el-button
        >
        <el-button
          type="primary"
          htmlType="button"
          icon="form"
          @click="submitForm"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
import {
  listGoods,
  goodsDel,
  goodsUpdate,
  goodsDetail,
  goodsAdd,
} from "@/api/api";
export default {
  data() {
    return {
      look: false,
      treeName: "",
      value: 6,
      expandOnClickNode: true,
      currSelected: {},
      // 展示右侧商品详细信息
      goodsList: [],
      options: {},
      loading: false,
      open: false,
      selectedKeys: [],
      form: {},
      // val: [],

      // 查询参数
      queryParams: {
        name: null,
      },
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
      },
      data: [],
      changeData: [],
      treeData: [],
      defaultProps: {
        //树形控件的属性绑定对象
        children: "children", //设置通过children属性展示子节点信息
        label: "title", //通过label设置树形节点文本展示
        checkStrictly: true,
      },
    };
  },
  created() {
    this.getTreeSelect();
  },
  methods: {
    treeDate() {
      this.look = false;
    },
    getTreeItem(data, name) {
      data.map((item, index) => {
        if (item.title == name) {
          this.look = true;
        } else {
          if (item.children) {
            this.getTreeItem(item.children, name);
          }
        }
      });
    },
    // 过滤删除树结构指定节点及其子节点
    filterTreeData(data, ids) {
      let newData = data.filter((x) => x.id !== ids);
      newData.forEach((x) => {
        if (x.children) {
          x.children = this.filterTreeData(x.children, ids);
        }
      });
      return newData;
    },
    updateRate() {
      listGoods().then((res) => {
        this.getTreeItem(res.data, this.form.name);
      });
    },
    // 四级菜单
    formatData(data) {
      let options = [];
      data.forEach((item, key) => {
        options.push({ label: item.title, value: item.id });
        if (item.children) {
          item.children.forEach((items, keys) => {
            options.push({ label: items.title, value: items.id });
            if (items.children) {
              items.children.forEach((itemss, keyss) => {
                options.push({ label: itemss.title, value: itemss.id });
                if (itemss.children) {
                  itemss.children.forEach((itemsss, keysss) => {
                    options.push({ label: itemsss.title, value: itemsss.id });
                  });
                }
              });
            }
          });
        }
      });
      return options;
    },
    // 修改清空下拉列表时触发
    setValueNull(){
      this.form.parentName ='';
      this.form.parentId = '';
    },
    handleNodeClick(node) {
      this.treeName = node.title;
      this.form.parentName = node.title;
      this.form.parentId = node.id;
      this.$refs.selectTree.blur();
    },
    // 树结构列表
    getTreeSelect() {
      listGoods().then((res) => {
        this.data = res.data;
        this.changeData = JSON.parse(JSON.stringify(this.data));
      });
    },
    // 递归
    getMenuChoose(children) {
      for (let item of children) {
        if (item.choose) {
          this.menuChoose.push(item.id);
        }
        if (item.children) {
          this.getMenuChoose(item.children);
        }
      }
    },
    // 接收被勾选的数据
    currentChecked(nodeObj, SelectedObj) {
      this.changeData = JSON.parse(JSON.stringify(this.data));
      goodsDetail(nodeObj.id).then((res) => {
        this.form = res.data;
        this.currSelected.title = this.form.name;
      });
      this.goodsList.push(SelectedObj.checkedKeys);
      this.selectedKeys = this.goodsList.slice(-1);
      this.changeData = this.filterTreeData(this.changeData, nodeObj.id);
    },
    // 确认删除
    handleDelete() {
      let delId = "";
      for (let i in this.selectedKeys) {
        delId += `${this.selectedKeys[i]}`;
      }
      this.$modal
        .confirm('是否确认删除"' + this.goodsList.length + '"项的数据？')
        .then(function () {
          return goodsDel(delId);
        })
        .then(() => {
          this.getTreeSelect();
          this.$modal.msgSuccess("删除成功");
          this.selectedKeys = {};
        })
        .catch(() => {});
    },
    handleAdd() {
      this.open = true;
      this.form = {};
    },
    // 获取选中的节点
    getCascaderObj(val, opt) {
      return val?.map(function (value, index, array) {
        // this.form.parentId = val
        for (var itm of opt) {
          if (itm.id == value) {
            opt = itm.children;
            return itm;
          }
        }
        return null;
      });
    },

    menuchange() {
      this.parentId = this.getCascaderObj(this.form.parentId, this.data).slice(
        -1
      )[0].id; //选中节点
      this.$refs.elcascader.dropDownVisible = false;
    },
    getCurrSelectedTitle() {
      return this.currSelected.title ? this.currSelected.title : "";
    },
    onClearSelected() {
      this.currSelected = {};
      this.goodsList.length = 0;
      this.$refs.tree.setCheckedKeys([]);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.form = {};
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        this.getTreeItem(this.data, this.form.name);
        if (this.look) {
          this.$message.error("名称已存在请重新填写");
        } else {
          if (valid) {
            let params = {
              name: this.form.name,
              parentId: this.form.parentId,
              remark: this.form.remark,
            };
            goodsAdd(params).then((res) => {
              if (res.code == 200) {
                this.data = res.data;
                this.getTreeSelect();
                this.$message.success("添加成功");
                this.open = false;
              }
            });
            this.form = {};
          }
        }
      });
    },

    Sure() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = {
            id: this.form.id,
            parentId: this.form.parentId,
            name: this.form.name,
            remark: this.form.remark,
            sort: this.form.sort,
          };
          goodsUpdate(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("保存成功！");
              this.getTreeSelect();
            }
          });
        }
      });
    },
    emptyCurrForm() {
      this.form.id = this.form.id;
      this.form.name = '';
      this.form.parentName = ''
      this.form.parentId = '';
      this.form.sort = '';
      this.form.remark = '';
    },
    refresh() {
      this.loading = true;
      this.getTreeSelect();
    },
  },
};
</script>

<style>
.el-icon-info:before {
  font-size: 18px;
  margin-right: 5px;
}
.el-alert--info.is-light {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  font-size: 10px;
}
.aform-btn {
  width: 100%;
  text-align: center;
}
.form-btn {
  /* background-color: green; */
  text-align: center;
}
.form-btn button {
  margin: 0 5px;
}
.input-border-style {
  border: 1px solid red;
  border-radius: 5px;
}
.drawer-bootom-button {
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}
.el-cascader-panel .el-radio__input {
  visibility: hidden;
}
.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>